<template>
  <div class="product-list">
    <!-- 添加按钮、模糊搜索、查询按钮 -->
    <!-- {{searchForm}}-------{{categoryData}} -->
    <!-- {{tableData}} -->
    <div class="search">
      <div>
        <el-button class="btn" type="primary" @click="toAdd">添加</el-button>
      </div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="产品名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.status"
            placeholder="产品状态"
            clearable
          >
            <el-option label="正常" value="正常" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.productCategoryId"
            placeholder="产品分类"
            clearable
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        stripe
      >
        <el-table-column label="序号" type="index" />
        <el-table-column prop="id" label="产品编号" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="photo" label="图片" width="50px" align="center">
          <template slot-scope="scope">
            <!-- {{scope.row.photo}} -->
            <!-- <img src="scope.row.photo" alt=""> -->
            <el-image
              style="width: 30px; height: 30px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          label="价格"
          align="center"
        />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <!-- <el-tag v-if="scope.row.status==='正常'" type="success">{{scope.row.status}}</el-tag> -->
            <!-- <el-tag v-else type="danger">{{scope.row.status}}</el-tag> -->
            <el-tag
              :type="scope.row.status === '正常' ? 'success' : 'danger'"
            >{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="category.name"
          label="所属栏目"
        />
        <el-table-column label="操作" width="140">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="toEdit(scope.row)"
            >编辑</el-button>
            <!-- <el-button
              type="text"
              size="small"
              :disabled="scope.row.status === '正常'"
              @click="toOnline(scope.row.id)"
            >上架</el-button>
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.status === '下架'"
              @click="toOffline(scope.row.id)"
            >下架</el-button> -->
            <el-button
              v-if="scope.row.status === '下架'"
              type="text"
              class="warning_info"
              size="small"
              @click="toOnline(scope.row.id)"
            >上架</el-button>
            <el-button
              v-if="scope.row.status === '正常'"
              type="text"
              size="small"
              class="warning_info"
              @click="toOffline(scope.row.id)"
            >下架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination-div">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 15, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 模态框 -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <!-- {{ form }} -->
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-form-item
          label="产品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="所属栏目"
          :label-width="formLabelWidth"
          prop="productCategoryId"
        >
          <el-select
            v-model="form.productCategoryId"
            placeholder="请选择所属栏目"
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model.number="form.price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth" prop="photo">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuery } from '@/api/proCategory'
import { pageQuery as pageQueryPro, saveOrUpdate, online, offline } from '@/api/product'
import { showFileURL, uploadFileURL } from '@/utils/config'
export default {
  data() {
    return {
      showFileURL,
      uploadFileURL,
      // 页面一上来，就发送请求，请求所有的产品栏目数据，设置到categoryData
      // 产品栏目的数据
      categoryData: [],
      // 模糊搜索表单的数据
      searchForm: {
        name: '',
        status: '',
        productCategoryId: ''
      },
      // 表格展示的数据
      tableData: [],
      // 分页参数
      params: {
        page: 1,
        pageSize: 10
      },
      // 总条数
      total: 0,
      // 加载
      loading: false,
      // 模态框的显示与隐藏
      visible: false,
      // 表单数据
      form: {},
      formLabelWidth: '80px',
      // 模态框标题
      title: '',
      imageUrl: '',
      rules: {
        name: [
          {
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }
        ],
        productCategoryId: [
          {
            required: true,
            message: '请选择所属栏目',
            trigger: 'change'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          },
          {
            type: 'number',
            message: '价格必须为数字值',
            trigger: 'blur'
          }
        ],
        photo: [
          {
            required: true,
            message: '请上传图片',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {},
  watch: {
    params: {
      handler() {
        this.queryData()
      },
      deep: true
    }
  },
  created() {
    // 发请求
    this.queryCategoryData()
    this.queryData()
  },
  mounted() {},
  methods: {
    // 获取产品分类数据
    async queryCategoryData() {
      const res = await pageQuery({ page: 1, pageSize: 100 })
      this.categoryData = res.data.list
      // console.log(res.data.list.name);
    },
    // 分页模糊获取产品数据
    async queryData() {
      this.loading = true
      // 处理数据
      const temp = {
        // 合并数据
        ...this.params,
        ...this.searchForm
      }
      // 遍历对象
      for (const key in temp) {
        // key是一个变量，代表的属性名
        // console.log(key, temp[key]);
        if (!temp[key]) {
          delete temp[key]
        }
      }
      const res = await pageQueryPro(temp)
      this.loading = false
      this.tableData = res.data.list
      this.total = res.data.total
    },
    // 查询按钮点击事件处理程序
    toSearch() {
      this.queryData()
    },
    // 每页显示的条数发生变化时的处理程序
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // this.params.pageSize = val;
      // this.params.page = 1;
      this.params = {
        pageSize: val,
        page: 1
      }
    },
    // 当前页码发生变化时的事件处理程序
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.params.page = val
    },
    // 添加按钮事件处理
    toAdd() {
      this.queryCategoryData()
      // 清空表单数据
      this.form = {}
      this.imageUrl = ''
      this.title = '添加产品消息'
      this.visible = true
    },
    // 图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      // console.log(res,"==图片上传成功的res");
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(this.imageUrl);
      this.form.photo = this.showFileURL + res.data.id
    },
    // 图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 模态框确定按钮事件处理程序
    toSave() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          console.log('校验通过')
          const res = await saveOrUpdate(this.form)
          // 提示用户保存成功，刷新表格数据，关闭模态框
          this.$notify.success({
            title: '成功',
            message: res.success
          })
          this.queryData()
          // this.toClose();
          this.visible = false
        } else {
          return false
        }
      })
    },
    toClose() {
      // 重置表单验证
      this.$refs.ruleForm.resetFields()
      // 超时调用,在多少毫秒后调用执行
      // setTimeout(() => {
      //   this.visible = false;
      // }, 100);
    },
    // 编辑按钮事件处理程序
    toEdit(row) {
      this.queryCategoryData()
      // 设置表单数据
      this.form = { ...row }
      this.imageUrl = this.form.photo
      this.title = '编辑产品消息'
      this.visible = true
    },
    // 上架产品
    async toOnline(id) {
      const res = await online({ id })
      this.$notify.success({
        title: '成功',
        message: res.message
      })
      this.queryData()
    },
    async toOffline(id) {
      const res = await offline({ id })
      this.$notify.success({
        title: '成功',
        message: res.message
      })
      this.queryData()
    }
  }
}
</script>
<style lang= "scss" scoped>
/* scss less css预处理器 */
/* .product-list{
    padding: 10px;
} */
.search {
  display: flex;
  /* height: 40px; */
  .btn {
    margin-right: 10px;
  }
}
</style>
